﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Nim.Game
{
    class NimBoard
    {
        private bool[,] board;

        public NimBoard()
        {
            board = new bool[3, 7];
        }

        //Allows you to remove a number of sticks from a certain row. Returns false if you can't remove sticks from a row
        public bool TakeFrom(int row, int number)
        {
            bool canTake = false;

            int sticksInRow = SticksInRow(row);

            if (number <= sticksInRow)
            {
                --sticksInRow;

                for (int i = 0; i < number; ++i)
                {
                    board[row, sticksInRow] = false;
                    --sticksInRow;
                }

                canTake = true;
            }

            return canTake;
        }

        //Sets the first 3 spots in the first row to true, then the first 5 in the second row, and then 7 on the third row
        public void Initialize()
        {
            int sticksInRow = 3;

            for (int i = 0; i < 3; ++i)
            {
                for (int j = 0; j < sticksInRow; ++j)
                {
                    board[i, j] = true;
                }
                sticksInRow += 2;
            }
        }

        //Draws the board to the console
        public void DrawBoard()
        {
            for (int i = 0; i < 3; ++i)
            {
                string row = "";

                for (int j = 0; j < 7; ++j)
                {
                    if (board[i, j]) row += " | ";
                }

                Console.WriteLine(row);
                Console.WriteLine();
            }
        }

        //Returns the number of sticks in a row
        public int SticksInRow(int row)
        {
            int sticksInRow = 0;

            for (int i = 0; i < 7; ++i)
            {
                if (board[row, i]) ++sticksInRow;
            }

            return sticksInRow;
        }

        //Checks if the row is empty or not
        public bool IsRowEmpty(int row)
        {
            bool isEmpty = false;

            isEmpty = SticksInRow(row) == 0;

            return isEmpty;
        }

        //Checks if the board is empty or not
        public bool IsBoardEmpty()
        {
            bool isEmpty = true;

            for (int i = 0; i < 3; ++i)
            {
                if (SticksInRow(i) > 0) isEmpty = false;
            }

            return isEmpty;
        }

        //Retuns a 3 character string which represents the state of the board
        public string GetBoardState()
        {
            string state = "";

            for (int i = 0; i < 3; ++i)
            {
                state += SticksInRow(i);
            }

            return state;
        }
    }
}
